package com.ruoyi.business.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.vo.DailyMealVO;
import com.ruoyi.common.core.domain.vo.MealInfoVO;
import com.ruoyi.common.utils.DayOfWeekToolUtils;
import com.ruoyi.business.mapper.WsdDishesMapper;
import com.ruoyi.business.mapper.WsdMealdishesMapper;
import com.ruoyi.business.mapper.WsdMealsMapper;
import com.ruoyi.business.service.IWsdMealsService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.mealDishesDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdMealdishes;
import com.ruoyi.common.core.domain.entity.WsdMeals;
import com.ruoyi.common.core.domain.vo.DailyMealPlanVO;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.date.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.time.format.TextStyle;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * <p>
 * 餐饮时间表 服务实现类
 * </p>
 *
 * @author wwq
 * @since 2024-04-20
 */
@Service
@Slf4j
public class WsdMealsServiceImpl extends ServiceImpl<WsdMealsMapper, WsdMeals> implements IWsdMealsService {

    @Autowired
    private WsdMealsMapper wsdMealsMapper;
    @Autowired
    private WsdMealdishesMapper wsdMealdishesMapper;
    @Autowired
    private WsdDishesMapper wsdDishesMapper;

    /**
     * 新增时间菜品信息
     *
     * @param mealDishesDto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult insertWsdMeals(mealDishesDTO mealDishesDto) {
        String dateString = mealDishesDto.getDate();
        LocalDate date = LocalDate.parse(dateString);  // 默认格式是 yyyy-MM-dd
        //获得星期
        String dayOfWeek = DayOfWeekToolUtils.getDayOfWeek(mealDishesDto.getDate());
        //获得学校
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        //新增早餐时间表
        WsdMeals wsdMeals = new WsdMeals();
        wsdMeals.setDate(date);
        wsdMeals.setDayOfWeek(dayOfWeek);
        wsdMeals.setMealType(0);
        wsdMeals.setStartTime(LocalTime.parse(mealDishesDto.getStartTime0()));
        wsdMeals.setEndTime(LocalTime.parse(mealDishesDto.getEndTime0()));
        wsdMeals.setSchoolId(schoolId);
        this.save(wsdMeals);
        //新增中间表
        for (Integer i : mealDishesDto.getDishes0()) {
            WsdMealdishes wsdMealdishes = new WsdMealdishes();
            wsdMealdishes.setMealId(wsdMeals.getMealId());
            wsdMealdishes.setDishId(i);
            wsdMealdishesMapper.insert(wsdMealdishes);
        }
        //新增午餐
        WsdMeals wsdMeals1 = new WsdMeals();
        wsdMeals1.setDate(date);
        wsdMeals1.setDayOfWeek(dayOfWeek);
        wsdMeals1.setMealType(1);
        wsdMeals1.setStartTime(LocalTime.parse(mealDishesDto.getStartTime1()));
        wsdMeals1.setEndTime(LocalTime.parse(mealDishesDto.getEndTime1()));
        wsdMeals1.setSchoolId(schoolId);
        this.save(wsdMeals1);
        //新增中间表
        for (Integer i : mealDishesDto.getDishes1()) {
            WsdMealdishes wsdMealdishes = new WsdMealdishes();
            wsdMealdishes.setMealId(wsdMeals1.getMealId());
            wsdMealdishes.setDishId(i);
            wsdMealdishesMapper.insert(wsdMealdishes);
        }
        //新增晚餐
        WsdMeals wsdMeals2 = new WsdMeals();
        wsdMeals2.setDate(date);
        wsdMeals2.setDayOfWeek(dayOfWeek);
        wsdMeals2.setMealType(2);
        wsdMeals2.setStartTime(LocalTime.parse(mealDishesDto.getStartTime2()));
        wsdMeals2.setEndTime(LocalTime.parse(mealDishesDto.getEndTime2()));
        wsdMeals2.setSchoolId(schoolId);
        this.save(wsdMeals2);
        //新增中间表
        for (Integer i : mealDishesDto.getDishes2()) {
            WsdMealdishes wsdMealdishes = new WsdMealdishes();
            wsdMealdishes.setMealId(wsdMeals2.getMealId());
            wsdMealdishes.setDishId(i);
            wsdMealdishesMapper.insert(wsdMealdishes);
        }
        return AjaxResult.success("新增成功");
    }

    /**
     * 查询学校食谱列表
     *
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public List<DailyMealPlanVO> selectWsdMealsList(String startDate, String endDate) {
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        List<DailyMealPlanVO> mealsByDateRange = wsdMealsMapper.findMealsByDateRange(startDate, endDate, schoolId);
        for (DailyMealPlanVO dailyMealPlanVO : mealsByDateRange) {
            System.out.println(dailyMealPlanVO);
        }
        return mealsByDateRange;
    }


    /**
     * 修改学校食谱
     *
     * @param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult updateWsdMeals(mealDishesDTO mealDishesDto) {
        //获得学校
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        //获得时间
        String dateString = mealDishesDto.getDate();
        LocalDate date = LocalDate.parse(dateString);  // 默认格式是 yyyy-MM-dd
        //根据时间查询
        LambdaQueryWrapper<WsdMeals> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WsdMeals::getSchoolId,schoolId);
        wrapper.eq(WsdMeals::getDate,date);
        List<WsdMeals> wsdMeal = wsdMealsMapper.selectList(wrapper);
        //删除中间表
        List<Integer> mealIds = wsdMeal.stream().map(WsdMeals::getMealId).collect(Collectors.toList());
        if (!mealIds.isEmpty()) {
            LambdaQueryWrapper<WsdMealdishes> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.in(WsdMealdishes::getMealId, mealIds);
            wsdMealdishesMapper.delete(wrapper1);
        }
        //删除时间表
        wsdMealsMapper.deleteBatchIds(mealIds);
        //新增早餐时间表
        //获得星期
        String dayOfWeek = DayOfWeekToolUtils.getDayOfWeek(mealDishesDto.getDate());
        WsdMeals wsdMeals = new WsdMeals();
        wsdMeals.setDate(date);
        wsdMeals.setDayOfWeek(dayOfWeek);
        wsdMeals.setMealType(0);
        wsdMeals.setStartTime(LocalTime.parse(mealDishesDto.getStartTime0()));
        wsdMeals.setEndTime(LocalTime.parse(mealDishesDto.getEndTime0()));
        wsdMeals.setSchoolId(schoolId);
        this.save(wsdMeals);
        //新增中间表
        for (Integer i : mealDishesDto.getDishes0()) {
            WsdMealdishes wsdMealdishes = new WsdMealdishes();
            wsdMealdishes.setMealId(wsdMeals.getMealId());
            wsdMealdishes.setDishId(i);
            wsdMealdishesMapper.insert(wsdMealdishes);
        }
        //新增午餐
        WsdMeals wsdMeals1 = new WsdMeals();
        wsdMeals1.setDate(date);
        wsdMeals1.setDayOfWeek(dayOfWeek);
        wsdMeals1.setMealType(1);
        wsdMeals1.setStartTime(LocalTime.parse(mealDishesDto.getStartTime1()));
        wsdMeals1.setEndTime(LocalTime.parse(mealDishesDto.getEndTime1()));
        wsdMeals1.setSchoolId(schoolId);
        this.save(wsdMeals1);
        //新增中间表
        for (Integer i : mealDishesDto.getDishes1()) {
            WsdMealdishes wsdMealdishes = new WsdMealdishes();
            wsdMealdishes.setMealId(wsdMeals1.getMealId());
            wsdMealdishes.setDishId(i);
            wsdMealdishesMapper.insert(wsdMealdishes);
        }
        //新增晚餐
        WsdMeals wsdMeals2 = new WsdMeals();
        wsdMeals2.setDate(date);
        wsdMeals2.setDayOfWeek(dayOfWeek);
        wsdMeals2.setMealType(2);
        wsdMeals2.setStartTime(LocalTime.parse(mealDishesDto.getStartTime2()));
        wsdMeals2.setEndTime(LocalTime.parse(mealDishesDto.getEndTime2()));
        wsdMeals2.setSchoolId(schoolId);
        this.save(wsdMeals2);
        //新增中间表
        for (Integer i : mealDishesDto.getDishes2()) {
            WsdMealdishes wsdMealdishes = new WsdMealdishes();
            wsdMealdishes.setMealId(wsdMeals2.getMealId());
            wsdMealdishes.setDishId(i);
            wsdMealdishesMapper.insert(wsdMealdishes);
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 获取食谱详细信息
     * @param specificDate
     * @param schoolId
     * @return
     */
    @Override
    public DailyMealVO selectWsdLeavesById(String specificDate, Long schoolId) {
        DailyMealVO dailyMealVO = wsdMealsMapper.selectWsdMealsById(specificDate,schoolId);
        dailyMealVO.setBreakfastDishIds(parseDishIdsString(dailyMealVO.getDishes0()));
        dailyMealVO.setLunchDishIds(parseDishIdsString(dailyMealVO.getDishes1()));
        dailyMealVO.setDinnerDishIds(parseDishIdsString(dailyMealVO.getDishes2()));
        return dailyMealVO;
    }

    /**
     * 装换数据
     * @param dishIdsStr
     * @return
     */
    private static List<Integer> parseDishIdsString(String dishIdsStr) {
        return Arrays.stream(dishIdsStr.split(","))
                .map(String::trim)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
    }

    /**
     * 删除学校食谱
     *
     * @param specificDate
     * @param schoolId
     * @return
     */
    @Override
    public int deleteWsdMealsByIds(String specificDate, Long schoolId) {
        //获得时间
        String dateString = specificDate;
        LocalDate date = LocalDate.parse(dateString);  // 默认格式是 yyyy-MM-dd
        //根据时间查询
        LambdaQueryWrapper<WsdMeals> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WsdMeals::getSchoolId,schoolId);
        wrapper.eq(WsdMeals::getDate,date);
        List<WsdMeals> wsdMeal = wsdMealsMapper.selectList(wrapper);
        //删除中间表
        List<Integer> mealIds = wsdMeal.stream().map(WsdMeals::getMealId).collect(Collectors.toList());
        if (!mealIds.isEmpty()) {
            LambdaQueryWrapper<WsdMealdishes> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.in(WsdMealdishes::getMealId, mealIds);
            wsdMealdishesMapper.delete(wrapper1);
        }
        //删除时间表
        return wsdMealsMapper.deleteBatchIds(mealIds);
    }



    /**
     * 查询当天学校食谱
     *
     * @param specificDate 期望查询的日期，格式为"yyyy-MM-dd"
     * @param schoolId 学校ID
     * @return 返回指定日期和学校的食谱信息列表
     */
    @Override
    public List<MealInfoVO> selectMealInfo(String specificDate, Long schoolId) {
        List<MealInfoVO> mealInfoVOS = new ArrayList<>();
        // 参数非空校验
        if (specificDate == null || schoolId == null) {
            throw new IllegalArgumentException("时间为空或者学校id为空");
        }
        try {
            // 日期解析，添加异常处理
            LocalDate localDate = LocalDate.parse(specificDate);
            List<MealInfoVO> mealInfoVOList = wsdMealsMapper.selectMealInfo(localDate, schoolId);
            // 返回值为空的处理
            if (mealInfoVOList == null) {
                return Collections.emptyList();
            }
            for (MealInfoVO mealInfoVO : mealInfoVOList) {
                MealInfoVO mealInfoVO1 = new MealInfoVO();
                BeanUtils.copyProperties(mealInfoVO, mealInfoVO1);
                mealInfoVO1.setDayOfWeek(DateTimeUtil.convertToEnglish(mealInfoVO.getDayOfWeek()));
                System.out.println(mealInfoVO1);
                mealInfoVOS.add(mealInfoVO1);
            }
            return mealInfoVOS;
        } catch (DateTimeParseException e) {
            // 日期格式异常处理
            log.error("日期格式异常处理" + e.getMessage());
            return Collections.emptyList();
        }
    }
}
